package org.streets.wicket.markup;

import org.apache.wicket.Component;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

import org.streets.wicket.event.AjaxUpdateEvent;
import org.streets.wicket.event.IAjaxUpdateListener;

public abstract class AjaxUpdateOnUpdatePanel extends Panel implements IAjaxUpdateListener {

	private static final long serialVersionUID = 1L;
	private Component _component;
	private WebMarkupContainer _container;

	public AjaxUpdateOnUpdatePanel(final String id) {
		super(id);
	}

	public AjaxUpdateOnUpdatePanel(final String id, final IModel model) {
		super(id, model);
	}
	//default construct
	{
		_container = new WebMarkupContainer("container");
		_container.setOutputMarkupId(true);
		add(_container);
	}

	public Component getComponent() {
		if (_component == null) {
			_container.add(_component = newComponent("component"));
		}
		return _component;
	}

	@Override
	protected void onBeforeRender() {
		getComponent();
		super.onBeforeRender();
	}

	public final void notifyAjaxUpdate(final AjaxUpdateEvent event) {
		if (update(event)) {
			event.getTarget().addComponent(getContainer());
		}
	}

	private Component getContainer() {		
		getComponent(); // init if necessary
		return _container;
	}

	protected abstract boolean update(final AjaxUpdateEvent event);

	protected abstract Component newComponent(String id);
}
